﻿using System;
using System.Collections.Generic;
using UnityEngine;

namespace Code.UI
{
    public class TabGroup : MonoBehaviour
    {
        public Transform tabButtonParent;
        public List<TabButton> tabButtons;
        public Sprite tabIdle;
        public Sprite tabHover;
        public Sprite tabActive;
        public TabButton selectedTab;
        public List<GameObject> objectsToSwap;
        private void Awake()
        {
            for (int i = 0; i < tabButtonParent.childCount; i++)
            {
                var tabButton = tabButtonParent.GetChild(i).GetComponent<TabButton>();
                Subscribe(tabButton);
                //tabButtons.Add(tabButton);
            }
        }

        private void Start()
        {
           
            OnTabSelected(tabButtons[0]);
        }

        public void Subscribe(TabButton button)
        {
            if (tabButtons == null)
            {
                tabButtons = new List<TabButton>();
            }
            tabButtons.Add(button);
        }

        public void OnTabEnter(TabButton button)
        {
            ResetTabs();
            if (selectedTab == null || button != selectedTab)
            {
                button.Background.sprite = tabHover;
            }
        }

        public void OnTabExit(TabButton button)
        {
            ResetTabs();
        }

        public void OnTabSelected(TabButton button)
        {
            if (selectedTab != null) { selectedTab.Deselect(); }
            selectedTab = button;
            selectedTab.Select();

            ResetTabs();
            button.Background.sprite = tabActive;
            int index = button.transform.GetSiblingIndex();
            for (int i = 0; i < objectsToSwap.Count; i++)
            {
                if (i == index)
                {
                    objectsToSwap[i].SetActive(true);
                }
                else
                {
                    objectsToSwap[i].SetActive(false);
                }
            }
        }
        public void ResetTabs()
        {
            foreach (var button in tabButtons)
            {
                if (selectedTab != null && button == selectedTab)
                {
                    continue;
                }
                button.Background.sprite = tabIdle;
            }
        }
    }
}
